//
//  vbo_vao.cpp
//  Sierpinski
//
//  Created by wneqi on 14-5-19.
//  Copyright (c) 2014年 wneqi. All rights reserved.
//

#include <stdio.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#define glGenVertexArrays glGenVertexArraysAPPLE
#define glBindVertexArray glBindVertexArrayAPPLE
#else
#include "GL/glew.h"  // must come before the other GL includes
#include <GL/glut.h>
#endif

/*注意，上面如果没有使用宏定义，而是用gl3.h的话，会有问题。创建的两个vao总是指向第2个vbo中的数据，不知为何。*/

#include "vbo_vao.h"

static float vertices[3][2] =
{
    {0, 0},
    {0, 1},
    {1, 0}
};
static float color[3][3] =
{
    {1, 0, 0},
    {0, 1, 0},
    {0, 0, 0}
};

static float another_vertices [3][2] =
{
    {0, 0},
    {0, -1},
    {-1, 0}
};
static float another_color[3][3] =
{
    {1, 0, 0},
    {0, 1, 0},
    {0, 0, 0}
};

static GLuint vbo[2];
static GLuint vao[2];

void init_vbo_vao_main (int argc, char** argv)
{
    glutInit (&argc, argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize (800, 600);
    glutInitWindowPosition (100, 100);
    glutCreateWindow ("Hello, VBO And VAO");
    glutDisplayFunc (display_vbo_vao);
    init_vbo_vao_gl ();
    glutMainLoop ();
}

void init_vbo_vao_gl ()
{
    // 构建vbo
    glGenBuffers (2, vbo);
    glGenVertexArrays (2, vao);
    
    // 设置第一个三角形的vbo
    glBindBuffer (GL_ARRAY_BUFFER, vbo[0]);
    // 提交第一个三角形的顶点和颜色数据到GPU中
    glBufferData (GL_ARRAY_BUFFER, sizeof (vertices) + sizeof (color), NULL, GL_STATIC_DRAW);
    glBufferSubData (GL_ARRAY_BUFFER, 0, sizeof (vertices), vertices);
    glBufferSubData (GL_ARRAY_BUFFER, sizeof (vertices), sizeof (color), color);
    
    // 设置第二个三角形的vbo
    glBindBuffer (GL_ARRAY_BUFFER, vbo[1]);
    glBufferData (GL_ARRAY_BUFFER, sizeof (another_vertices) + sizeof (another_color), NULL, GL_STATIC_DRAW);
    glBufferSubData (GL_ARRAY_BUFFER, 0, sizeof (another_vertices), another_vertices);
    glBufferSubData (GL_ARRAY_BUFFER, sizeof (another_vertices), sizeof (another_color), another_color);
    
    
    // 构建vao，并将相应的vbo和其中数据绑定到vao的相应数据段中
    
    // 绑定第一个三角形的vao和vbo
    glBindVertexArray (vao[0]);
    glEnableClientState (GL_VERTEX_ARRAY);
    glEnableClientState (GL_COLOR_ARRAY);
    glBindBuffer (GL_ARRAY_BUFFER, vbo[0]);
    glVertexPointer (2, GL_FLOAT, 0, 0);
    glColorPointer (3, GL_FLOAT, 0, (GLvoid*) (sizeof (vertices)));
    
    // 绑定第二个三角形的vao和vbo
    glBindVertexArray (vao[1]);
    glEnableClientState (GL_VERTEX_ARRAY);
    glEnableClientState (GL_COLOR_ARRAY);
    glBindBuffer (GL_ARRAY_BUFFER, vbo[1]);
    glVertexPointer (2, GL_FLOAT, 0, 0);
    glColorPointer (3, GL_FLOAT, 0, (GLvoid*)(sizeof (another_vertices)));
    
    glClearColor (1, 1, 1, 1);
    
}

void display_vbo_vao ()
{
    glClear (GL_COLOR_BUFFER_BIT);
    
    // 绘制第一个三角形
    glBindVertexArray (vao[0]);
    glDrawArrays (GL_TRIANGLES, 0, 3);
    
    // 绘制第二个三角形
    glBindVertexArray (vao[1]);
    glDrawArrays (GL_TRIANGLES, 0, 3);
    
     
    glFlush ();
}















